package com.shwread.android.qysw.activity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.bean.TrainCoursewareBean;
import logic.bean.TrainCoursewareListBean;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.PicassoUtil;
import logic.util.Util;
import logic.util.Utils;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.customview.MyGridView;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.TrainActionHelp;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.squareup.picasso.Picasso;
import com.tgx.tina.android.task.ATaskService;


public class SearchThemeActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener,
        TextWatcher {
    private MyGridView gridView1;
    private EditText etSearch;
    private Button searchClose;
    private TextView searchOrBack;
    private RelativeLayout searchRl, rlay_loading, searchNull;
    private PullToRefreshScrollView contentView;
    private ImageView loadingImg;
    private int currentPage = 1;
    private int length = 10;
    private AnimationDrawable animationDrawable;
    private GridViewAdapter gridViewAdapter;
    private Context context;
    private List<TrainCoursewareListBean> trainList = new ArrayList<TrainCoursewareListBean>();

    // 隐藏系统输入法
    InputMethodManager mInputMethodManager;

    Handler myHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.theme_search);
        context = this;
        mAService = new ATaskService();
        mAService.startAService(this);
        initView();
        setListener();
    }

    private void setListener() {
        // TODO Auto-generated method stub
        searchClose.setOnClickListener(this);
        etSearch.addTextChangedListener(this);
        searchOrBack.setOnClickListener(this);
        searchRl.setOnClickListener(this);
        contentView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (contentView.isHeaderShown()) {
                    refrush();
                } else if (contentView.isFooterShown()) {
                    loadMore();
                }
            }

        });
        gridView1.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                // TODO Auto-generated method stub
                String cid = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getTrainIndexCid();
                Intent intent = new Intent(context, TrainExamCommonWebActivity.class);
                // 传模块标题
                //				intent.putExtra(DefaultConsts.title_s, getDetailTitle(modelType));
                //课件深入到课件详情
                TrainCoursewareListBean bean = ((TrainCoursewareListBean) arg0.getAdapter().getItem(arg2));
                intent.putExtra(DefaultConsts.title_s, "");
                intent.putExtra(DefaultConsts.req_url_s, getCourseWareUrl(bean.trainId, bean.trainType, cid));
                startActivity(intent);
            }
        });

    }

    private String getCourseWareUrl(int trainId, int trainType, String cid) {
        return TrainActionHelp.getUrl() + "toTrainChapterList.do?trainId=" + trainId + "&trainType=" + trainType + "&cid=" + cid;
    }

    private void initView() {
        gridView1 = (MyGridView) findViewById(R.id.search_theme_content_1_listview);
        gridView1.setVisibility(View.VISIBLE);
        etSearch = (EditText) findViewById(R.id.search_theme_editText);
        searchClose = (Button) findViewById(R.id.search_theme_close_content);
        searchOrBack = (TextView) findViewById(R.id.search_quxiao_tv);
        searchRl = (RelativeLayout) findViewById(R.id.search_theme_rl);
        searchNull = (RelativeLayout) findViewById(R.id.search_theme_null);
        contentView = (PullToRefreshScrollView) findViewById(R.id.search_theme_psview);
        PullToRefreshUtil.initLabel(this, contentView);
        //加载动画
        rlay_loading = (RelativeLayout) findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) findViewById(R.id.common_loading__img);

        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        Util.showInputMethodManager(this);
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.search_theme_close_content:
                etSearch.setText("");
                break;
            case R.id.search_quxiao_tv:
                if (searchOrBack.getText().equals("取消")) {
                    finish();
                    Util.hideInputMethodManager(this, etSearch);
                } else if (searchOrBack.getText().equals("搜索")) {
                    searchOrBack.setText("取消");
                    trainList.clear();
                    currentPage = 1;
                    startLoading();
                    String cid = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getTrainIndexCid();
                    TrainActionHelp.qryTrainSearchList(context, etSearch.getText().toString().trim(), cid, currentPage, length, new GetTrainSeaarchList());
                }
                break;
            case R.id.search_theme_rl:
                mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                Util.showInputMethodManager(this);
                break;

            default:
                break;
        }
    }

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub
        myHandler.post(new Runnable() {

            @Override
            public void run() {
                if (Utils.isEmpty(etSearch.getText().toString().trim())) {
                    searchOrBack.setText("取消");
                    searchClose.setVisibility(View.GONE);
                } else {
                    searchOrBack.setText("搜索");
                    searchClose.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private Handler handler = new Handler();

    private void initData() {
        if (gridViewAdapter == null) {
            gridViewAdapter = new GridViewAdapter();
            gridView1.setAdapter(gridViewAdapter);
        }
        gridViewAdapter.notifyDataSetChanged();
        Util.hideInputMethodManager(this, etSearch);
        stopLoading();
    }

    class GridViewAdapter
            extends
            BaseAdapter {

        private TrainCoursewareHolder holder;

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return trainList.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return trainList.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup arg2) {
            TrainCoursewareListBean listBean = trainList.get(position);
            if (view == null) {
                holder = new TrainCoursewareHolder();
                view = LayoutInflater.from(context).inflate(R.layout.new_trainexam_content_item_new, null);
                holder.view1 = view.findViewById(R.id.new_trainexam_content_item_ll1);
                holder.view1.setVisibility(View.VISIBLE);
                holder.view2 = view.findViewById(R.id.new_trainexam_content_item_ll2);
                holder.view2.setVisibility(View.GONE);
                holder.tvTitle = (TextView) view.findViewById(R.id.new_trainexam_content_item_title);
                holder.tvTitle.setLines(2);
                holder.sivImage = (ImageView) view.findViewById(R.id.new_trainexam_content_item_image);
                PicassoUtil.load(context, R.drawable.trainexam_default_img, holder.sivImage);
                holder.tvCount = (TextView) view.findViewById(R.id.new_trainexam_content_item_count);
                holder.tvTime = (TextView) view.findViewById(R.id.new_trainexam_content_item_time);
                holder.ivVedio = (ImageView) view.findViewById(R.id.new_trainexam_content_img);
                view.setTag(holder);
            } else {
                holder = (TrainCoursewareHolder) view.getTag();
            }
            if (listBean == null)
                return view;
            if (listBean.trainType == 3) {
                holder.ivVedio.setVisibility(View.GONE);
            } else {
                holder.ivVedio.setVisibility(View.GONE);
            }
            holder.tvTitle.setText(listBean.name);
            //holder.tvIntro.setText(listBean.shortIntro); // 去掉简介字段
//            holder.sivImage.setImageUrl(listBean.coverImg1);
            PicassoUtil.load(context, listBean.coverImg1,R.drawable.trainexam_default_img,holder.sivImage);
			/*
			 * holder.tvCount.setText("集数:" + listBean.chapterNum);
			 * if (Utils.isEmpty(listBean.lecturerName))
			 * holder.tvTime.setVisibility(View.GONE);
			 * else
			 * holder.tvTime.setText("讲师:" + listBean.lecturerName);
			 */
            holder.tvTime.setVisibility(View.GONE);
            if (Utils.isEmpty(listBean.typeName)) {
                holder.tvCount.setText("类型:" + "");
            } else {
                holder.tvCount.setText("类型:" + listBean.typeName);
            }
            return view;
        }

    }

    private class TrainCoursewareHolder {
        TextView tvIntro, tvAuthor;
        ImageView sivImage;                                                           // ok
        ImageView ivVedio;                                                               // ok
        View view1, view2, view3;                                                   // view1,view2 ok

        TextView tvTitle, tvRight, tvWrong, tvScore, tvHandTime, tvUsedTime, tvRedo; // ok
        TextView tvCount, tvTime;                                                       // ok
    }

    private class GetTrainSeaarchList
            extends
            ObjectHttpResponseHandler<TrainCoursewareBean> {

        @Override
        public Type getType() {
            // TODO Auto-generated method stub
            return new TypeToken<TrainCoursewareBean>() {
            }.getType();
        }

        @Override
        public void onFailure(final int arg0, Header[] arg1, String arg2, Throwable arg3) {
            System.out.println("onFailure-------code*******" + arg0);
            getUIHandler().post(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    searchNull.setVisibility(View.VISIBLE);
                    gridView1.setVisibility(View.GONE);// 内容为空
                }
            });
        }

        @Override
        public void onSuccess(final int arg0, Header[] arg1, final TrainCoursewareBean arg2, String arg3) {
            System.out.println("onSuccess-------code*******" + arg0);
            getUIHandler().post(new Runnable() {

                @Override
                public void run() {
                    if (arg2.trainList == null || arg2.trainList.size() == 0) {
                        // 取到的内空为空
                        if (currentPage == 1) {// 只有当前是重新刷新时，
                            // 才更新ui为无内容
                            searchNull.setVisibility(View.VISIBLE);
                            gridView1.setVisibility(View.GONE);// 内容为空
                            Util.hideInputMethodManager(SearchThemeActivity.this, etSearch);
                        } else {
                            currentPage--;
                        }
                        stopLoading();
                        contentView.onRefreshComplete();
                        return;
                    } else {
                        searchNull.setVisibility(View.GONE);
                        gridView1.setVisibility(View.VISIBLE);
                    }
                    if (currentPage == 1) {// 刷新
                        trainList = arg2.trainList;
                    } else {// 取下一页
                        trainList.addAll(arg2.trainList);
                        //						PullToRefreshUtil.setLoadLabel(contentView, "加载成功");
                    }
                    initData();
                    contentView.onRefreshComplete();
                }
            });
        }
    }

    @Override
    public Handler getUIHandler() {
        // TODO Auto-generated method stub
        return handler;
    }

    /******************** 一些辅助性的方法 ****************************************/

    /**
     * 上拉加载
     */
    private void loadMore() {
        //		Utils.showToast(bActivity, "下拉加载");
        //		PullToRefreshUtil.setLoadLabel(contentView, "正在加载中");
        currentPage++;
        String cid = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getTrainIndexCid();
        TrainActionHelp.qryTrainSearchList(context, etSearch.getText().toString().trim(), cid, currentPage, length, new GetTrainSeaarchList());

    }

    /**
     * 下拉刷新
     */
    private void refrush() {
        currentPage = 1;
        //		new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener(1)).start();
        String cid = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getTrainIndexCid();
        TrainActionHelp.qryTrainSearchList(context, etSearch.getText().toString().trim(), cid, currentPage, length, new GetTrainSeaarchList());
    }

    //	private void loadSuccess() {
    //		if (currentPage == 1)
    //		{// 刷新
    //			updateSwitchView(1);// 隐藏动画
    //			if (contentViewListener != null)
    //			{
    //				contentViewListener.OnLoadDataCompleted(1);
    //			}
    //		}
    //		else
    //		{// 取下一页
    //			if (contentViewListener != null)
    //			{
    //				contentViewListener.OnLoadDataCompleted(2);// 装载更多
    //			}
    //		}
    //	}

    /**
     * 回到顶部
     */
    private void gotoTop() {
        contentView.post(new Runnable() {
            @Override
            public void run() {
                contentView.getRefreshableView().scrollTo(0, 0);
            }
        });
    }

    /**
     * 开始加载动画
     */
    private void startLoading() {
        rlay_loading.setVisibility(View.VISIBLE);
        loadingImg.setBackgroundResource(R.drawable.home_progress);
        animationDrawable = (AnimationDrawable) loadingImg.getBackground();
        animationDrawable.start();
    }

    /**
     * 停止加载动画
     */
    private void stopLoading() {
        rlay_loading.setVisibility(View.GONE);
        if (animationDrawable != null && animationDrawable.isRunning()) {
            animationDrawable.stop();
        }
    }

    /**
     * 关闭加载的动画
     * int a 0 为首次进入 关闭加载动画 1 为contentView 事件
     */
    private void closeLoading(int a) {
        if (a == 0) {
            stopLoading();
        } else {
            contentView.onRefreshComplete();
        }

    }

}
